/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pt.ua.miect.sd.simuladorpesca.client;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import org.apache.log4j.Logger;
import pt.ua.miect.sd.simuladorpesca.config.NodeService;
import pt.ua.miect.sd.simuladorpesca.config.ServiceConfig;
import pt.ua.miect.sd.simuladorpesca.config.SimulationConfig;
import pt.ua.miect.sd.simuladorpesca.conns.SocketMessage;
import pt.ua.miect.sd.simuladorpesca.conns.SocketMessageType;
import pt.ua.miect.sd.simuladorpesca.conns.SocketWrapper;
import pt.ua.miect.sd.simuladorpesca.conns.VectorClock;

/**
 * Creates a Node that is waiting for connections to be established
 * @author PedroA
 */
public class ClientNode implements Runnable {

    private ServerSocket ssocket;
    private Logger logger;
    private SimulationConfig config;
    private NodeService service;
    private VectorClock logicalClock;

    /***
     * Creates a client Node and waits for connections at the given port
     * @param port
     * @throws IOException
     */
    public ClientNode(int port) throws IOException {
        ssocket = new ServerSocket(port);
        logger = Logger.getLogger(ClientNode.class);
    }

    @Override
    public void run() {
        SocketWrapper sw = null;
        try {
            Socket con = ssocket.accept();
            sw = new SocketWrapper(con, NodeService.Server);
            logger.info(String.format("Connection established: %s ; %d", con.getLocalAddress(), con.getPort()));
        } catch (IOException ex) {
            logger.fatal(ex);
            return;
        }
        try {
            SocketMessage sm = (SocketMessage) sw.getIn().readObject();
            if (sm.getType() == SocketMessageType.SimulationConfig) {
                config = (SimulationConfig) sm.getContent();
                logger.info("Receving Config");
                ServiceConfig myservice = config.getService(sw.getSocket().getLocalAddress().toString(), sw.getSocket().getLocalPort());
                if (myservice != null) {
                    service = myservice.getService();
                    logger.info("Client role:" + service);
                    sw.getOut().writeObject(new SocketMessage(null, SocketMessageType.Acknowledge, config));
                } else {
                    logger.error("Failed to receive role!");
                }
            } else {
                logger.error("Failed to receive the Simulation Config");
            }
        } catch (IOException ex) {
            logger.fatal(ex);
            return;
        } catch (ClassNotFoundException ex) {
            logger.fatal(ex);
            return;
        }



    }
}
